
const {insertUser,getUser, editUser, delUser,searchUser} = require('../model/user.model')

class UserService{
  // 注册
  async createUser(user_name, pass_word) {
    // 插入数据
    const params = {username: user_name, password: pass_word}
    const res = await insertUser('b_user', params);
    return res;
  }
  // 登陆
  async getUserInfo({id, user_name, pass_word}) {
    // 第一个参数是需要返回的字段名，第二个参数是表名，第三参数是条件名，第四个参数时条件值
    // const params = [['id', 'username', 'password'], 'b_user', 'username', user_name]; 
    // const params = {username: user_name}
    const whereOpt = {}

    id && Object.assign(whereOpt, { id })
    user_name && Object.assign(whereOpt, { username: user_name })
    pass_word && Object.assign(whereOpt, { password: pass_word })

    const res = await getUser('b_user', whereOpt);
    return res.length > 0 ? res : null;
  }
  // 修改密码
  async edit(id, pass_word) {
    const params = {password: pass_word}
    const whereJosn = {id: id}
    const res = await editUser('b_user', params, whereJosn);
    return res;
  }
  // 删除用户
  async del(id) {
    const params = {id: id}
    const res = await delUser('b_user', params);
    return res;
  }
  //查询用户列表
  async search({ pageNum, pageSize }) {
    const page = (pageNum-1) * pageSize;

    // 分页
    let whereLimit = `limit ${page}, ${pageSize}`;
    
    const sql = `select * from b_user ${whereLimit}`;
    const res = await searchUser(sql)
    return res
  }
  // 查询用户总数
  async searchUserTotal() {
   
    const sql = `select count(*) as total from b_user`;
    const res = await searchUser(sql)
    return res
  }
}

module.exports = new UserService()
